<template>
  <div class="courses-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="课程号">
          <el-input
            v-model="searchForm.cno"
            placeholder="请输入课程号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="课程名">
          <el-input
            v-model="searchForm.cname"
            placeholder="请输入课程名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="教师">
          <el-input
            v-model="searchForm.teacher"
            placeholder="请输入教师姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增课程
          </el-button>
          <el-button type="warning" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出Excel
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="cno" label="课程号" width="120" />
        <el-table-column prop="cname" label="课程名" width="300" />
        <el-table-column prop="teacher" label="教师" width="150" />
        <el-table-column prop="credit" label="学分" width="100" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              type="info"
              size="small"
              @click="handleViewDetails(row)"
            >
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程号" prop="cno">
              <el-input
                v-model="form.cno"
                placeholder="请输入课程号"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程名" prop="cname">
              <el-input v-model="form.cname" placeholder="请输入课程名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="教师" prop="teacher">
              <el-input v-model="form.teacher" placeholder="请输入教师姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学分" prop="credit">
              <el-input-number
                v-model="form.credit"
                :min="1"
                :max="10"
                placeholder="请输入学分"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 课程详情对话框 -->
    <el-dialog
      title="课程详情"
      v-model="detailsVisible"
      width="800px"
    >
      <div v-if="courseDetails">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="课程号">{{ courseDetails.cno }}</el-descriptions-item>
          <el-descriptions-item label="课程名">{{ courseDetails.cname }}</el-descriptions-item>
          <el-descriptions-item label="教师">{{ courseDetails.teacher }}</el-descriptions-item>
          <el-descriptions-item label="学分">{{ courseDetails.credit }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="course-stats" v-if="courseStats">
          <h3>课程统计</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-statistic title="选课人数" :value="courseStats.enrollmentCount" />
            </el-col>
            <el-col :span="8">
              <el-statistic title="平均成绩" :value="courseStats.averageScore" :precision="1" />
            </el-col>
            <el-col :span="8">
              <el-statistic title="及格率" :value="courseStats.passRate" suffix="%" :precision="1" />
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, View, Download } from '@element-plus/icons-vue'
import { courseApi, enrollmentApi } from '@/api'
import * as XLSX from 'xlsx'

export default {
  name: 'Courses',
  components: {
    Search,
    Refresh,
    Plus,
    Edit,
    Delete,
    View,
    Download
  },
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const detailsVisible = ref(false)
    const isEdit = ref(false)
    const formRef = ref()
    
    const searchForm = reactive({
      cno: '',
      cname: '',
      teacher: ''
    })
    
    const form = reactive({
      cno: '',
      cname: '',
      teacher: '',
      credit: null
    })
    
    const tableData = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const courseDetails = ref(null)
    const courseStats = ref(null)
    
    const dialogTitle = computed(() => {
      return isEdit.value ? '编辑课程' : '新增课程'
    })
    
    const rules = {
      cno: [
        { required: true, message: '请输入课程号', trigger: 'blur' },
        { min: 2, max: 10, message: '课程号长度在2-10个字符', trigger: 'blur' }
      ],
      cname: [
        { required: true, message: '请输入课程名', trigger: 'blur' },
        { min: 2, max: 30, message: '课程名长度在2-30个字符', trigger: 'blur' }
      ],
      credit: [
        { required: true, message: '请输入学分', trigger: 'blur' },
        { type: 'number', min: 1, max: 10, message: '学分应在1-10之间', trigger: 'blur' }
      ],
      teacher: [
        { required: true, message: '请输入教师姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '教师姓名长度在2-10个字符', trigger: 'blur' }
      ]
    }
    
    // 加载课程数据
    const loadData = async () => {
      loading.value = true
      try {
        // 构建筛选参数，只传递有值的参数
        const params = {}
        if (searchForm.cno && searchForm.cno.trim()) {
          params.cno = searchForm.cno.trim()
        }
        if (searchForm.cname && searchForm.cname.trim()) {
          params.cname = searchForm.cname.trim()
        }
        if (searchForm.teacher && searchForm.teacher.trim()) {
          params.teacher = searchForm.teacher.trim()
        }
        
        console.log('前端发送课程筛选参数:', params)
        const response = await courseApi.getCourses(params)
        if (response.code === 200) {
          tableData.value = response.data.records || response.data || []
          total.value = response.data.total || response.data.length || 0
        }
      } catch (error) {
        console.error('加载课程数据失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      loadData()
    }
    
    // 重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      loadData()
    }
    
    // 新增
    const handleAdd = () => {
      isEdit.value = false
      dialogVisible.value = true
      resetForm()
    }
    
    // 编辑
    const handleEdit = (row) => {
      isEdit.value = true
      dialogVisible.value = true
      Object.keys(form).forEach(key => {
        form[key] = row[key]
      })
    }
    
    // 查看详情
    const handleViewDetails = async (row) => {
      try {
        // 获取课程详情
        const detailsResponse = await courseApi.getCourseDetails(row.cno)
        if (detailsResponse.code === 200) {
          courseDetails.value = detailsResponse.data
        }
        
        // 获取课程统计信息
        const statsResponse = await courseApi.getCourseStats(row.cno)
        if (statsResponse.code === 200) {
          courseStats.value = statsResponse.data
        }
        
        detailsVisible.value = true
      } catch (error) {
        console.error('获取课程详情失败:', error)
      }
    }
    
    // 删除
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除课程 ${row.cname}(${row.cno}) 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await courseApi.deleteCourse(row.cno)
          if (response.code === 200) {
            ElMessage.success('删除成功')
            loadData()
          }
        } catch (error) {
          console.error('删除失败:', error)
        }
      })
    }
    
    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        submitLoading.value = true
        
        let response
        if (isEdit.value) {
          response = await courseApi.updateCourse(form.cno, form)
        } else {
          response = await courseApi.addCourse(form)
        }
        
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
          dialogVisible.value = false
          loadData()
        }
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      Object.keys(form).forEach(key => {
        form[key] = key === 'credit' ? null : ''
      })
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }
    
    // 关闭对话框
    const handleDialogClose = () => {
      resetForm()
    }
    
    // 分页大小改变
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      loadData()
    }
    
    // 当前页改变
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadData()
    }
    
    // 导出Excel
    const handleExport = () => {
      try {
        const exportData = tableData.value.map(item => ({
          '课程号': item.cno,
          '课程名': item.cname,
          '教师': item.teacher,
          '学分': item.credit
        }))
        
        const ws = XLSX.utils.json_to_sheet(exportData)
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, '课程列表')
        
        const fileName = `课程列表_${new Date().toISOString().slice(0, 10)}.xlsx`
        XLSX.writeFile(wb, fileName)
        
        ElMessage.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
      }
    }
    
    onMounted(() => {
      loadData()
    })
    
    return {
      loading,
      submitLoading,
      dialogVisible,
      detailsVisible,
      isEdit,
      formRef,
      searchForm,
      form,
      tableData,
      currentPage,
      pageSize,
      total,
      courseDetails,
      courseStats,
      dialogTitle,
      rules,
      handleSearch,
      handleReset,
      handleAdd,
      handleEdit,
      handleViewDetails,
      handleDelete,
      handleSubmit,
      handleDialogClose,
      handleSizeChange,
      handleCurrentChange,
      handleExport
    }
  }
}
</script>

<style scoped>
.courses-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.table-card {
  background: white;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

.course-stats {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.course-stats h3 {
  margin-bottom: 15px;
  color: #333;
}

:deep(.el-form-item) {
  margin-bottom: 15px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  text-align: left !important;
}

:deep(.el-table td) {
  text-align: left !important;
}

:deep(.el-table .cell) {
  text-align: left !important;
}
</style>